package com.reins.bookstore.controller;

import com.reins.bookstore.object.Filter;
import com.reins.bookstore.object.OneBookOrder;
import com.reins.bookstore.object.ThreeBooksOrder;
import com.reins.bookstore.object.OrderDTO;
import com.reins.bookstore.service.OrderService;
import com.reins.bookstore.utils.pageutils.Page;
import com.reins.bookstore.utils.pageutils.PageUtil;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;

@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;



    @RequestMapping("/findAllOrders")
    public Page findAllOrders(@RequestBody Filter filter){
        if (filter.getUserId() == null)
            filter.setUserId(0);
        if (filter.getPages() == null)
            filter.setPages(1);

        List<OrderDTO> res = new LinkedList<>();
        res = orderService.findAllOrders(filter);


        JSONArray data = JSONArray.fromObject(res);
        Page result = PageUtil.makePage(filter.getPages(),data);
        return result;
    }
    @RequestMapping("/findAllGlobalOrders")
    public List<OrderDTO> findAllGlobalOrders(){
        List<OrderDTO> res = orderService.findGlobalOrders();
        return res;
    }

    @RequestMapping("/buyOneBook")
    public BigDecimal BuyOneBook(@RequestBody OneBookOrder params){
        BigDecimal res;
        try {
            res = orderService.buyOneBook(params);
        }
        catch (Exception ex)
        {
            return null;
        }
        return res;
    }

    @RequestMapping("/buyThreeBooks")
    public BigDecimal BuyThreeBook(@RequestBody ThreeBooksOrder params){
        BigDecimal res;
        try {
            res = orderService.buyThreeBooks(params);
        }
        catch (Exception ex)
        {
            return  null;
        }
        return res;
    }
}
